﻿using Abp.Application.Services;
using Abp.UI;
using Hangfire;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace Mes5GService.MES
{
    public class MesAppService : AbpZeroTemplateAppServiceBase, IMesAppService
    {
        private readonly IWebHostEnvironment webHostEnvironment;
        public MesAppService(IWebHostEnvironment webHostEnvironment)
        {
            this.webHostEnvironment = webHostEnvironment;
        }
        public async Task ImportFromZip(IFormFile file)
        {
            try
            {
                string fileOriginName = file.FileName;

                string web_path = webHostEnvironment.ContentRootPath;

                DirectoryInfo di = new DirectoryInfo(web_path + "/import");
                if (!di.Exists)
                {
                    di.Create();
                }
                string extension = Path.GetExtension(fileOriginName);
                if (!extension.Equals(".zip"))
                {
                    throw new UserFriendlyException("文件类型错误，必须为.zip文件");
                }
                string outputFileName = Guid.NewGuid().ToString() + extension;
                string outputFilePath = web_path + "/import/" + outputFileName;
                Stream stream = file.OpenReadStream();
                FileStream outputStream = new FileStream(outputFilePath, FileMode.OpenOrCreate);
                await stream.CopyToAsync(outputStream);
                outputStream.Close();
                BackgroundJob.Enqueue<ImportTask>(r => r.Import(outputFilePath));
            }
            catch(Exception ex)
            {
                throw new UserFriendlyException($"文件上传失败：{ex.Message}");
            }
        }
    }
}
